<?php

namespace addons\qingdongams\controller;

use addons\qingdongams\model\Approval as ApprovalModel;
use addons\qingdongams\model\ExamineRecord;
use addons\qingdongams\model\FormApproval;
use addons\qingdongams\model\Form;
use addons\qingdongams\model\FormField;
use addons\qingdongams\model\Message;
use think\Db;
use think\Exception;

/**
 * 工作审批
 */
class Approval extends StaffApi {
	protected $noNeedLogin = [];
	protected $noNeedRight = [];

	//审批数量
    public function examineApprovalNumber()
    {
        $whereFlow = [];
        $where = [];
        $where['check_status'] = ['in', [0, 1]];
        $whereFlow['next_staff_id'] = $this->auth->id;
        $woshenhe = ApprovalModel::where($where)->where($whereFlow)->count();

        $where['create_staff_id'] = $this->auth->id;
        //我发起的
        $wofaqi = ApprovalModel::where($where)->count();


        $this->success('请求成功', ['wofaqi' => $wofaqi, 'woshenhe' => $woshenhe]);
    }
	//审核审核记录
	public function examineApprovalList(){
        $check_status=input('check_status');//1审核中、2审核通过、3审核未通过
        $type=input('type',1);
        $whereFlow=$followWhere = [];
        $where=[];

        if ($check_status) {
            //0待审核、1审核中、2审核通过、3审核未通过、4撤销
            if ($check_status == 1) {
                $where['check_status'] = ['in', [0, 1]];
                $followWhere['next_staff_id'] = $this->auth->id;
            } elseif ($check_status == 2) {
                $where['check_status'] = 2;
                $followWhere[] = ['exp', Db::raw('FIND_IN_SET(' . $this->auth->id. ',check_staff_ids)')];
            } elseif ($check_status == 3) {
                $where['check_status'] = 3;
                $followWhere[] = ['exp', Db::raw('FIND_IN_SET(' . $this->auth->id. ',check_staff_ids)')];
            } elseif ($check_status == 4) {
                $where['check_status'] = 4;
                $followWhere[] = ['exp', Db::raw('FIND_IN_SET(' . $this->auth->id. ',check_staff_ids)')];
            } elseif ($check_status == 9) {
                $where['check_status'] = 9;
                $followWhere[] = ['exp', Db::raw('FIND_IN_SET(' . $this->auth->id. ',check_staff_ids)')];
            }
        }
        if($type == 1){//我发起的
            $where['create_staff_id']=$this->auth->id;
        }elseif($type == 2){//我审批的
            $whereFlow = $followWhere;
        }

        $approvals= ApprovalModel::where($where)->where($whereFlow)->with(['createStaff','formapproval'])->order('id desc')->paginate();

       $this->success('请求成功',$approvals);
    }


    /**
     * 获取工作列表
     */
	public function getList() {
        $list = FormApproval::where([])->field('id,name,img')->select();

		$this->success('请求成功', $list);
	}


    /**
     * 获取form表单
     */
	public function getFormapproval() {
		$id = input('id');

		$form = FormApproval::where(['id' => $id])->find();
        $formData = Form::where(array('id'=>$form['form_id']))->find();
        $staff = \addons\qingdongams\model\Staff::where(['id' => ['in',explode(',', $form['flow_staff_ids'])],'status'=>1])->field('id,name,img')->select();
        $data=json_decode($formData['data'], true)['data']??[];
		$this->success('请求成功',['data'=>$data,'staff'=>$staff] );
	}


    /**
     * 添加审批
     */
	public function addApproval() {
		$params          = $this->request->post();
        if(empty( $params['data'])){
            $this->error('数据不能为空');
        }
        if(empty( $params['formapproval_id'])){
            $this->error('表单id不能为空');
        }
        if(empty( $params['relation_type'])){
            $this->error('关联类型不能为空');
        }
        $approval=FormApproval::where(['id'=>$params['formapproval_id']])->with(['form'])->find();
        $result = FormField::checkFields($approval['form']['type'], $params['data']);
        if ($result !== true) {
            $this->error($result);
        }
		ApprovalModel::createApproval($params);

		$this->success('请求成功');
	}

    /**
     * 获取审批详情
     */
	public function getDetail(){
        $id       = input('id');
        if(empty($id)){
            $this->error('参数不能为空');
        }
        $approval=ApprovalModel::where(['id'=>$id])->find()->toArray();
        if ($approval['check_status'] == 0 || $approval['check_status'] == 1) {
            $approval['is_examine'] = ExamineRecord::isExaminse(ExamineRecord::APPROVAL_TYPE, $id);
        } else {
            $approval['is_examine'] = 0;
        }
        $approval['is_operation']=0;
        if($approval['create_staff_id'] == $this->auth->id){
            //是否可以操作
            $approval['is_operation']=1;
        }
        $form=FormApproval::where(['id'=>$approval['formapproval_id']])->with(['form'])->find();

        $approval['content'] = Form::getDataDetail($form['form']['type'], $approval['content']);
        Message::setRead(Message::APPROVAL_TYPE,$id,$this->auth->id);
        $this->success('请求成功',$approval);
    }

    /**
     * 修改审批
     */
    public function editApproval(){
        $id     = input('id');
        $params = $this->request->post();
        $row    = ApprovalModel::where(['id' => $id, 'check_status' => ['in', [3, 4]]])->find();
        if (empty($row)) {
            $this->error('审批信息不存在');
        }
        if(empty( $params['data'])){
            $this->error('数据不能为空');
        }
        if(empty( $params['formapproval_id'])){
            $this->error('表单id不能为空');
        }
        if(empty( $params['relation_type'])){
            $this->error('关联类型不能为空');
        }
        $approval=FormApproval::where(['id'=>$params['formapproval_id']])->with(['form'])->find();
        $result = FormField::checkFields($approval['form']['type'], $params['data']);
        if ($result !== true) {
            $this->error($result);
        }
        Db::startTrans();
        try {
            $result = ApprovalModel::updateApproval($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('修改信息成功');
    }

    /**
     * 撤回审批
     */
	public function cancel(){
        $id       = input('id');
        $customer = ApprovalModel::where([
            'id' => $id,
            'check_status' => ['in', [0, 1]],
            'create_staff_id'=>$this->auth->id])->find();
        if (empty($customer)) {
            $this->error('信息不存在');
        }

        Db::startTrans();
        try {

            ApprovalModel::where(['id' => $id])->update(['check_status' => 4]);

            ExamineRecord::cancelExaminse(ExamineRecord::APPROVAL_TYPE,$id);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();;
            $this->error($e->getMessage());
        }


        $this->success('撤回成功');
    }


    /**
     * 终止审批
     */
    public function revokeApproval()
    {
        $id = input('id');
        if(empty($id)){
            $this->error('id不能为空');
        }
        Db::startTrans();
        try {

            ApprovalModel::where(['id'=>$id])->update(['check_status'=>9]);

            ExamineRecord::cancelExaminse(ExamineRecord::APPROVAL_TYPE,$id);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('撤销成功');
    }
}
